package com.bss.command;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.bss.beans.DailyRevenue;
import com.bss.beans.Paymentsmade;
import com.bss.beans.RoomAllocation;
import com.bss.dao.CheckInOutDao;
import com.bss.dao.PaymentDao;
import com.bss.dao.RoomDao;
import com.bss.framework.FrontController;
import com.bss.utilities.DateUtilities;

public class PaymentCommand extends AbstractCommand {

	@Override
	public boolean execute(HttpServletRequest request, HttpSession session)
			throws Exception {

		// TODO Auto-generated method stub
		if (Integer.parseInt((session.getAttribute("action")).toString()) == 1) {
			if (findPaymentDate(request, session) == false) {
				return false;
			} else {
				session.removeAttribute("Error");
				return true;
			}
		} else if (Integer
				.parseInt((session.getAttribute("action")).toString()) == 2) {
			if (findPaymentAmount(request, session) == false) {

				return false;
			} else {
				session.removeAttribute("Error");
				return true;
			}
		} else if (Integer
				.parseInt((session.getAttribute("action")).toString()) == 3) {
			if (makePayment(request, session) == false) {

				return false;
			} else {
				session.removeAttribute("Error");
				return true;
			}
		} else if (Integer
				.parseInt((session.getAttribute("action")).toString()) == 4) {
			if (findPaymentmade(request, session) == false) {

				return false;
			} else {
				session.removeAttribute("Error");
				return true;
			}
		} else if (Integer
				.parseInt((session.getAttribute("action")).toString()) == 5) {
			if (generateDailyDepositAndRefundReport(request, session) == false) {
				return false;
			} else {
				session.removeAttribute("Error");
				return true;
			}
		} else if (Integer
				.parseInt((session.getAttribute("action")).toString()) == 6) {
			if (updateDailyRevenue(request, session) == false) {
				return false;
			} else {
				session.removeAttribute("Error");
				return true;
			}
		}
		return true;
	}

	@Override
	public boolean falseforward(HttpServletResponse response,
			HttpSession session) throws Exception {

		if (Integer.parseInt((session.getAttribute("action")).toString()) == 1) {
			session.setAttribute("welcomemsg", "UNABLE TO MAKE PATIENT PAYMENT");
			response.sendRedirect("checkinout.jsp");
		}

		else if (Integer.parseInt((session.getAttribute("action")).toString()) == 2) {
			if (session.getAttribute("Error") == null) {
				session.setAttribute("welcomemsg",
						"UNABLE COLLECT PAYMENT FROM PATIENT");
				response.sendRedirect("checkinout.jsp");
			} else {
				response.sendRedirect("CHECKINOUT/selectpaymentdate.jsp");
			}
		} else if (Integer
				.parseInt((session.getAttribute("action")).toString()) == 3) {
			session.setAttribute("welcomemsg", "UNABLE TO MAKE PATIENT PAYMENT");
			response.sendRedirect("checkinout.jsp");
		} else if (Integer
				.parseInt((session.getAttribute("action")).toString()) == 4) {
			if (session.getAttribute("Error") == null) {
				session.setAttribute("welcomemsg",
						"UNABLE TO GENERATE PAYMENT DETAILS");
				response.sendRedirect("checkinout.jsp");
			} else {
				response.sendRedirect("CHECKINOUT/selectpatientforreceipt.jsp");
			}
		} else if (Integer
				.parseInt((session.getAttribute("action")).toString()) == 5) {
			response.getWriter()
					.println(
							"<h2>Updating Daily Deposit Refund failed: "
									+ session.getAttribute("Error")
									+ "</h2><br/><a href='/BSS/reports.jsp'>Back to Reports</a>");
		} else if (Integer
				.parseInt((session.getAttribute("action")).toString()) == 6) {
			response.getWriter()
					.println(
							"<h2>Updating Daily Revenue Failed: "
									+ session.getAttribute("Error")
									+ "</h2><br/><a href='/BSS/reports.jsp'>Back to Reports</a>");
		}

		return true;
	}

	@Override
	public boolean trueforward(HttpServletResponse response, HttpSession session)
			throws Exception {

		if (Integer.parseInt((session.getAttribute("action")).toString()) == 1) {
			response.sendRedirect("CHECKINOUT/selectpaymentdate.jsp");
		} else if (Integer
				.parseInt((session.getAttribute("action")).toString()) == 2) {
			response.sendRedirect("CHECKINOUT/paytheamount.jsp");
		} else if (Integer
				.parseInt((session.getAttribute("action")).toString()) == 3) {
			session.setAttribute(
					"welcomemsg",
					"<h2> PATIENT PAYMENT SUCESSFULL </h2><br><h3> <a href='CHECKINOUT/cashreceipt.jsp?id="
							+ session.getAttribute("receiptId").toString()
							+ "'>GENERATE RECEIPT</a></h3>");
			response.sendRedirect("checkinout.jsp");
		} else if (Integer
				.parseInt((session.getAttribute("action")).toString()) == 4) {
			response.sendRedirect("CHECKINOUT/selectreceipttransactionId.jsp");
		} else if (Integer
				.parseInt((session.getAttribute("action")).toString()) == 5) {
			response.sendRedirect("DailyDepositAndRefundForm.jsp");
		} else if (Integer
				.parseInt((session.getAttribute("action")).toString()) == 6) {
			response.sendRedirect("TodaysRevenue.jsp");
		}

		return true;
	}

	private boolean findPaymentDate(HttpServletRequest request,
			HttpSession session) throws Exception {
		String date = "";
		session.setAttribute("patientId", request.getParameter("patientId"));
		int transactionId = CheckInOutDao.findLastTransactionId(Integer
				.parseInt(request.getParameter("patientId")));
		com.bss.framework.FrontController.trace("payment transactionid:" + transactionId);
		date = loadLastPaymentDate(transactionId);
		if (date.length() == 0) {
			return false;
		} else {
			session.setAttribute("transactionId", transactionId);
			session.setAttribute("paymentdate", date);

		}

		return true;
	}

	private boolean findPaymentAmount(HttpServletRequest request,
			HttpSession session) throws Exception {
		String date1 = request.getParameter("fromdate").toString();
		String date2 = request.getParameter("date").toString();
		ArrayList<RoomAllocation> getAlloc = RoomDao.getPatientStay(Integer
				.parseInt(session.getAttribute("transactionId").toString()));
		ArrayList<RoomAllocation> calAlloc = new ArrayList<RoomAllocation>();
		ArrayList<String> allocDates = new ArrayList<String>();
		ArrayList<String> releaseDates = new ArrayList<String>();
		int dateDiff = DateUtilities.findDateDiff(date1, date2);
		int isDomOver = 0;
		int isRoomOver = 0;
		int amount = 0;
		int days = 0;
		String doms = "";
		String rooms = "";
		if (dateDiff < 0) {
			session.setAttribute("Error", "Invalid UPTO PAYMENT Date Selection");
			return false;
		}

		for (int i = 0; i < getAlloc.size(); i++) {
			if (allocDates.contains(getAlloc.get(i).getSDateOfStay()) == false) {
				allocDates.add(getAlloc.get(i).getSDateOfStay());
				releaseDates.add(getAlloc.get(i).getSDateofcheckout());
			}
		}

		for (int j = 0; j < allocDates.size(); j++) {
			isDomOver = 0;
			isRoomOver = 0;
			for (int i = 0; i < getAlloc.size(); i++) {
				if (getAlloc.get(i).getSDateOfStay()
						.compareTo(allocDates.get(j)) == 0) {
					if (getAlloc.get(i).getIDomId() != 0 && isDomOver == 0) {
						isDomOver++;
						if (getAlloc.get(i).getSDateofcheckout() == null) {
							days = DateUtilities.noDaysDiffIn2Sets(
									date1,
									date2,
									DateUtilities.dbDateToCalDate(getAlloc.get(
											i).getSDateOfStay()), date2);
							days++;
						} else {
							days = DateUtilities.noDaysDiffIn2Sets(
									date1,
									date2,
									DateUtilities.dbDateToCalDate(getAlloc.get(
											i).getSDateOfStay()),
									DateUtilities.dbDateToCalDate(getAlloc.get(
											i).getSDateofcheckout()));
							days++;
						}
						if (days > 0) {
							amount += (days * getAlloc.get(i).getIAmount());
							doms += getAlloc.get(i).getIDomId() + "("
									+ getAlloc.get(i).getIRoomId() + ")("
									+ days + ")("
									+ getAlloc.get(i).getIAmount() + "),";
						}
					} else if (getAlloc.get(i).getIRoomId() != 0
							&& isRoomOver == 0
							&& getAlloc.get(i).getIDomId() == 0) {
						isRoomOver++;
						if (getAlloc.get(i).getSDateofcheckout() == null) {
							days = DateUtilities.noDaysDiffIn2Sets(
									date1,
									date2,
									DateUtilities.dbDateToCalDate(getAlloc.get(
											i).getSDateOfStay()), date2);
							days++;
						} else {
							days = DateUtilities.noDaysDiffIn2Sets(
									date1,
									date2,
									DateUtilities.dbDateToCalDate(getAlloc.get(
											i).getSDateOfStay()),
									DateUtilities.dbDateToCalDate(getAlloc.get(
											i).getSDateofcheckout()));
							days++;
						}
						if (days > 0) {
							amount += (days * getAlloc.get(i).getIAmount());
							rooms += getAlloc.get(i).getIRoomId() + "(" + days
									+ ")(" + getAlloc.get(i).getIAmount()
									+ "),";
						}
					} else if (getAlloc.get(i).getIDomId() != 0
							&& isDomOver > 0) {

						isDomOver++;
						if (getAlloc.get(i).getSDateofcheckout() == null) {
							days = DateUtilities.noDaysDiffIn2Sets(
									date1,
									date2,
									DateUtilities.dbDateToCalDate(getAlloc.get(
											i).getSDateOfStay()), date2);
							days++;
						} else {
							days = DateUtilities.noDaysDiffIn2Sets(
									date1,
									date2,
									DateUtilities.dbDateToCalDate(getAlloc.get(
											i).getSDateOfStay()),
									DateUtilities.dbDateToCalDate(getAlloc.get(
											i).getSDateofcheckout()));
							days++;
						}
						if (days > 0) {
							doms += getAlloc.get(i).getIDomId() + "("
									+ getAlloc.get(i).getIRoomId() + ")("
									+ days + ")("
									+ getAlloc.get(i).getIAmount() + "),";
						}
					}
				}
			}

		}
		com.bss.framework.FrontController.trace(doms);
		com.bss.framework.FrontController.trace(rooms);
		com.bss.framework.FrontController.trace("fromdate:" + date1);
		com.bss.framework.FrontController.trace("todate:" + DateUtilities.decCalDateBf8AM(date2));
		session.setAttribute("fromdate", date1);
		session.setAttribute("todate", DateUtilities.decCalDateBf8AM(date2));
		session.setAttribute("doms", doms);
		session.setAttribute("rooms", rooms);
		session.setAttribute("amount", amount);
		session.setAttribute("days", dateDiff + 1);
		return true;
	}

	public static String loadLastPaymentDate(int transactionId)
			throws Exception {
		String date = "";

		if ((date = PaymentDao.findLastPaymentDate(transactionId)).length() == 0) {

			date = DateUtilities.dbDateToCalDate((CheckInOutDao
					.findDateOfStay(transactionId)));
		} else {
			date = DateUtilities.incDbDateToCalDate(date);
		}

		return date;
	}

	private boolean makePayment(HttpServletRequest request, HttpSession session)
			throws Exception {
		Paymentsmade payment = new Paymentsmade();

		payment.setAmount(Integer.parseInt(session.getAttribute("amount")
				.toString()));
		payment.setDoms(session.getAttribute("doms").toString());
		payment.setNoOfDays(Integer.parseInt(session.getAttribute("days")
				.toString()));
		payment.setPaymentDate(request.getParameter("date").toString());
		payment.setPaymentFrom(session.getAttribute("fromdate").toString());
		payment.setPaymentId(PaymentDao.FindMaxPaymentId() + 1);
		payment.setPaymentUpto(session.getAttribute("todate").toString());
		payment.setRooms(session.getAttribute("rooms").toString());
		payment.setTransactionId(Integer.parseInt(session.getAttribute(
				"transactionId").toString()));

		PaymentDao.addPayment(payment);
		

		ArrayList<Integer> transactionIds = CheckInOutCommand
				.findAllTransactionId(Integer.parseInt(session.getAttribute(
						"patientId").toString()));
		
		FrontController.audit("Payment for Patient: " + session.getAttribute(
		"patientId").toString() + " from " + payment.getPaymentFrom() + " to "
				+ payment.getPaymentUpto() + ", PaymentId: " + payment.getPaymentId() + ", Amount: " + payment.getAmount());
		
		ArrayList<Paymentsmade> payments = PaymentDao
				.paymentsMade(transactionIds);
		session.setAttribute("payments", payments);
		session.setAttribute("receiptId", payment.getPaymentId());
		return true;
	}

	private boolean findPaymentmade(HttpServletRequest request,
			HttpSession session) throws Exception {
		int patientId = Integer.parseInt(request.getParameter("patientId")
				.toString());
		ArrayList<Integer> transactionIds = CheckInOutCommand
				.findAllTransactionId(patientId);

		ArrayList<Paymentsmade> payments = PaymentDao
				.paymentsMade(transactionIds);

		if (payments.size() == 0) {
			session.setAttribute("Error", "NO PAYMENTS MADE BY PAYMENT");
			return false;
		} else {
			session.setAttribute("payments", payments);
		}

		return true;

	}

	public static ArrayList<Integer> paymentDueList() throws Exception {
		ArrayList<Integer> transactionId = CheckInOutDao
				.loadCheckedInTransactionId();
		ArrayList<Integer> patientId = CheckInOutDao.loadCheckedInPatientId();
		ArrayList<Integer> duePatientId = new ArrayList<Integer>();
		String lastPayDate = "";

		for (int i = 0; i < transactionId.size(); i++) {
			DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm aaa");
			java.util.Date date = new java.util.Date();
			String datetime = dateFormat.format(date);
			String lastPayDbDate = PaymentDao.findLastPaymentDate(transactionId
					.get(i));
			com.bss.framework.FrontController.trace("--------------date is:"
					+ lastPayDbDate.length());
			if (lastPayDbDate != null && lastPayDbDate.length() != 0) {
				lastPayDate = com.bss.utilities.DateUtilities
						.dbDateToCalDate(lastPayDbDate);
			} else {
				lastPayDate = com.bss.utilities.DateUtilities
						.dbDateToCalDate(CheckInOutDao
								.findDateOfStay(transactionId.get(i)));
			}

			if (DateUtilities.findDateDiff(lastPayDate, datetime) > 7) {
				duePatientId.add(patientId.get(i));
			}
		}

		return duePatientId;
	}

	protected boolean generateDailyDepositAndRefundReport(
			HttpServletRequest request, HttpSession session) throws Exception {

		String dateFrom = DateUtilities.dbDateToCalDate(PaymentDao
				.latestDailyAccountReportDate());

		String dateTo = request.getParameter("date").toString();

		com.bss.framework.FrontController.trace("datefrom:" + dateFrom);

		if (DateUtilities.findNormalDateDiff(dateFrom, dateTo) <= 0) {
			com.bss.framework.FrontController.trace("fromDate:" + dateFrom + "--date to:" + dateTo
					+ "---sub:"
					+ DateUtilities.findNormalDateDiff(dateFrom, dateTo));
			session.setAttribute("Error",
					"Report Already Generated Of the given day");
			return false;
		}

		if (dateFrom == null || dateFrom.length() == 0) {
			session.setAttribute("Error", "Invalid Date of Report Genereation");
			return false;
		}

		session.setAttribute("date", dateTo);

		String depositTransactionIdRange = CheckInOutDao.findCheckedinIdRange(
				dateFrom, dateTo);

		int totalDeposit = 0;

		if (depositTransactionIdRange.length() == 0) {
			depositTransactionIdRange = "NIL";
		} else {
			totalDeposit = CheckInOutDao.findCheckedinDepsoit(dateFrom, dateTo);
		}

		session.setAttribute("depositTransactionIdRange",
				depositTransactionIdRange);
		session.setAttribute("totalDeposit", totalDeposit);

		session.setAttribute("totalDeposit", totalDeposit);
		session.setAttribute("depositTransactionIdRange",
				depositTransactionIdRange);

		ArrayList<Integer> paientIdUtensilAllocated = new ArrayList<Integer>();
		ArrayList<Integer> amountIdUtensilAllocated = new ArrayList<Integer>();
		CheckInOutDao.findUtensilAllocation(dateFrom, dateTo,
				paientIdUtensilAllocated, amountIdUtensilAllocated);

		
		int max = 0;
		

		max = paientIdUtensilAllocated.size() > max ? paientIdUtensilAllocated.size() : max;
		
		ArrayList<Integer> paientIdUtensilDeAllocated = new ArrayList<Integer>();
		ArrayList<Integer> amountIdUtensilDeAllocated = new ArrayList<Integer>();
		CheckInOutDao.findUtensilDeAllocation(dateFrom, dateTo,
				paientIdUtensilDeAllocated, amountIdUtensilDeAllocated);
		
		
		max = paientIdUtensilDeAllocated.size() > max ? paientIdUtensilDeAllocated.size() : max;

		ArrayList<Integer> transactionIdCheckOut = new ArrayList<Integer>();
		ArrayList<Integer> amountCheckOut = new ArrayList<Integer>();
		CheckInOutDao.findCheckoutList(dateFrom, dateTo, transactionIdCheckOut,
				amountCheckOut);

		if (transactionIdCheckOut.size() > 30) {  // MEANING LESS
			//session.setAttribute("Error", "No of Check Out Limit Exceeded: Maximum allowed 30...");
			//return false;
			
		}
		
		max = transactionIdCheckOut.size() > max ? transactionIdCheckOut.size() : max;

		session.setAttribute("paientIdUtensilAllocated",
				paientIdUtensilAllocated);
		session.setAttribute("amountIdUtensilAllocated",
				amountIdUtensilAllocated);
		session.setAttribute("paientIdUtensilDeAllocated",
				paientIdUtensilDeAllocated);
		session.setAttribute("amountIdUtensilDeAllocated",
				amountIdUtensilDeAllocated);
		session.setAttribute("transactionIdCheckOut", transactionIdCheckOut);
		session.setAttribute("amountCheckOut", amountCheckOut);
		session.setAttribute("allRecords", new String[max] );

		int totalDepositReturned = 0;
		for (int i = 0; i < amountCheckOut.size(); i++) {
			totalDepositReturned += amountCheckOut.get(i);
		}
		session.setAttribute("totalDepositReturned", totalDepositReturned);

		int totalUtensilDeposit = 0;
		for (int i = 0; i < amountIdUtensilAllocated.size(); i++) {
			totalUtensilDeposit += amountIdUtensilAllocated.get(i);
		}
		session.setAttribute("totalUtensilDeposit", totalUtensilDeposit);

		int totalUtensilDepositReturned = 0;
		for (int i = 0; i < amountIdUtensilDeAllocated.size(); i++) {
			totalUtensilDepositReturned += amountIdUtensilDeAllocated.get(i);
		}
		session.setAttribute("totalUtensilDepositReturned",
				totalUtensilDepositReturned);

		int openingBalanceUtensil = PaymentDao
				.dailyAccountClosingBalUtensil(dateTo);
		session.setAttribute("openingBalanceUtensil", openingBalanceUtensil);

		int openingBalanceRoom = PaymentDao.dailyAccountClosingBalRoom(dateTo);
		session.setAttribute("openingBalanceRoom", openingBalanceRoom);

		int closingBalanceUtensil = openingBalanceUtensil + totalUtensilDeposit
				- totalUtensilDepositReturned;
		session.setAttribute("closingBalanceUtensil", closingBalanceUtensil);

		int closingBalanceRoom = openingBalanceRoom + totalDeposit
				- totalDepositReturned;
		session.setAttribute("closingBalanceRoom", closingBalanceRoom);

		int deposit3 = totalDeposit - totalDepositReturned; // G = X - Y
		session.setAttribute("deposit3", deposit3);

		int deposit6 = totalUtensilDeposit - totalUtensilDepositReturned; // H =
																			// UD
																			// -
																			// UR
		com.bss.framework.FrontController.trace("deposit6;" + deposit6);
		session.setAttribute("deposit6", deposit6);

		int finalCashBalance = deposit3 + deposit6; // Final Balance = G + H
		session.setAttribute("finalCashBalance", finalCashBalance);

		
		 getPaymentDao().updateDailyAccountRecord(session);
		
		
		return true;
	}

	protected boolean updateDailyRevenue(HttpServletRequest request,
			HttpSession session) throws Exception {

		String lastReportDate = PaymentDao.latestDailyRevenueReportDate();

		if (lastReportDate.equals(""))
			lastReportDate = PaymentDao.latestDailyAccountReportDate();

		String dateFrom = DateUtilities.dbDateToCalDate(lastReportDate);

		String dateTo = request.getParameter("date").toString();
		com.bss.framework.FrontController.trace("datefrom:" + dateFrom);

		int receiptAmount = 0;

		DailyRevenue dailyRevenue = new DailyRevenue();

		if (DateUtilities.findNormalDateDiff(dateFrom, dateTo) <= 0) {
			com.bss.framework.FrontController.trace("fromDate:" + dateFrom + "--date to:" + dateTo
					+ "---sub:"
					+ DateUtilities.findNormalDateDiff(dateFrom, dateTo));
			session.setAttribute("Error", "Daily Revenue already updated...");
			return false;
		}

		if (dateFrom == null || dateFrom.length() == 0) {
			session.setAttribute("Error", "Invalid Date for Update !");
			return false;
		}

		int startRcptId = PaymentDao.oldestReceiptNo(dateFrom, dateTo);
		int stopRcptId = PaymentDao.latestReceiptNo(dateFrom, dateTo);

		dailyRevenue.setwReceiptStart(startRcptId);
		dailyRevenue.setwReceiptEnd(stopRcptId);

		receiptAmount = PaymentDao.totalCollectionAmount(startRcptId,
				stopRcptId);

		dailyRevenue.setReceiptTotal(receiptAmount);

		dailyRevenue.setDateGenerated(dateTo);

		if (request.getParameter("col1a") != null) {
			if (request.getParameter("col1a").toString().length() == 0) {
				dailyRevenue.setRasoiMorning(0);
			} else {
				dailyRevenue.setRasoiMorning(Integer.valueOf(request
						.getParameter("col1a").toString()));
			}
		}
		if (request.getParameter("col2a") != null) {
			if (request.getParameter("col2a").toString().length() == 0) {
				dailyRevenue.setRasoiEvening(0);
			} else {
				dailyRevenue.setRasoiEvening(Integer.valueOf(request
						.getParameter("col2a").toString()));
			}
		}

		if (request.getParameter("col5a") != null) {
			if (request.getParameter("col5a").toString().length() == 0) {
				dailyRevenue.setBusMorning(0);
			} else {
				dailyRevenue.setBusMorning(Integer.valueOf(request
						.getParameter("col5a").toString()));
			}
		}
		if (request.getParameter("col6a") != null) {
			if (request.getParameter("col6a").toString().length() == 0) {
				dailyRevenue.setBusAfternoon(0);
			} else {
				dailyRevenue.setBusAfternoon(Integer.valueOf(request
						.getParameter("col6a").toString()));
			}
		}
		
		if (request.getParameter("col7a") != null) {
			if (request.getParameter("col7a").toString().length() == 0) {
				dailyRevenue.setBusMini(0);
			} else {
				dailyRevenue.setBusMini(Integer.valueOf(request.getParameter(
						"col7a").toString()));
			}
		}
		
		if (request.getParameter("col8a") != null) {
			if (request.getParameter("col8a").toString().length() == 0) {
				dailyRevenue.setBusEvening(0);
			} else {
				dailyRevenue.setBusEvening(Integer.valueOf(request
						.getParameter("col8a").toString()));
			}
		}

		if (request.getParameter("col9a") != null) {
			dailyRevenue.setAmbulanceDetail1(request.getParameter("col9a"));
		}

		if (request.getParameter("col9b") != null) {
			if (request.getParameter("col9b").toString().length() == 0) {
				dailyRevenue.setAmbulanceRevenue1(0);
			} else {
				dailyRevenue.setAmbulanceRevenue1(Integer.valueOf(request
						.getParameter("col9b").toString()));
			}
		}
		
		if (request.getParameter("col10a") != null) {
			dailyRevenue.setAmbulanceDetail2(request.getParameter("col10a")
					.toString());
		}
		
		if (request.getParameter("col10b") != null) {
			if (request.getParameter("col10b").toString().length() == 0) {
				dailyRevenue.setAmbulanceRevenue2(0);
			} else {
				dailyRevenue.setAmbulanceRevenue2(Integer.valueOf(request
						.getParameter("col10b").toString()));
			}
		}

		if (request.getParameter("col11Others") != null) {
			dailyRevenue.setOthersDetail1(request.getParameter("col11Others"));
		}

		if (request.getParameter("col11a") != null) {
			if (request.getParameter("col11a").toString().length() > 0) {
				dailyRevenue.setOthersRevenue1(Integer.valueOf(request
						.getParameter("col11a").toString()));
			} else {
				dailyRevenue.setOthersRevenue1(0);
			}
		}

		if (request.getParameter("col12Others") != null) {
			dailyRevenue.setOthersDetail2(request.getParameter("col12Others"));
		}

		if (request.getParameter("col12a") != null) {
			if (request.getParameter("col12a").toString().length() > 0) {
				dailyRevenue.setOthersRevenue2(Integer.valueOf(request
						.getParameter("col12a").toString()));
			} else {
				dailyRevenue.setOthersRevenue2(0);
			}
		}

		dailyRevenue.setTotal(dailyRevenue.getRasoiMorning()
				+ dailyRevenue.getRasoiEvening() + dailyRevenue.getBusMorning()
				+ dailyRevenue.getBusAfternoon() + dailyRevenue.getBusEvening()
				+ dailyRevenue.getBusMini()
				+ dailyRevenue.getAmbulanceRevenue1()
				+ dailyRevenue.getAmbulanceRevenue2()
				+ dailyRevenue.getOthersRevenue1()
				+ dailyRevenue.getOthersRevenue2()
				+ dailyRevenue.getReceiptTotal());

		boolean result = getPaymentDao().update(dailyRevenue);
		
		FrontController.audit("Payment Updated: " + dateFrom + " to "
				+ dateTo + ", Receipt: " + startRcptId + " to "
				+ stopRcptId + ", Receipt Amount: " + receiptAmount+ ", Total: "+ dailyRevenue.getTotal()+ ", Rasoi: "+ dailyRevenue.getRasoiEvening());
		
		if (result)
			session.setAttribute("todaysRevenue", dailyRevenue);
		return result;
	}

	protected PaymentDao getPaymentDao() {
		return new PaymentDao();
	}

	public static boolean claculatePaymentAmount(String date2,
			int transactionId, HttpSession session) throws Exception {
		// String date1=request.getParameter("fromdate").toString();
		// String date2=request.getParameter("date").toString();
		// ArrayList<RoomAllocation>
		// getAlloc=RoomDao.getPatientStay(Integer.parseInt(session.getAttribute("transactionId").toString()));
		String date1 = PaymentCommand.loadLastPaymentDate(transactionId);
		ArrayList<RoomAllocation> getAlloc = RoomDao
				.getPatientStay(transactionId);
		ArrayList<RoomAllocation> calAlloc = new ArrayList<RoomAllocation>();
		ArrayList<String> allocDates = new ArrayList<String>();
		ArrayList<String> releaseDates = new ArrayList<String>();
		int dateDiff = DateUtilities.findDateDiff(date1, date2);
		int isDomOver = 0;
		int isRoomOver = 0;
		int amount = 0;
		int days = 0;
		String doms = "";
		String rooms = "";
		if (dateDiff < 0) {
			com.bss.framework.FrontController.trace("invalid upto payment date selected");
			session.setAttribute("Error", "Invalid UPTO PAYMENT Date Selection");
			session.setAttribute("amount", amount);
			return false;
		}

		for (int i = 0; i < getAlloc.size(); i++) {
			if (allocDates.contains(getAlloc.get(i).getSDateOfStay()) == false) {
				allocDates.add(getAlloc.get(i).getSDateOfStay());
				releaseDates.add(getAlloc.get(i).getSDateofcheckout());
			}
		}

		for (int j = 0; j < allocDates.size(); j++) {
			isDomOver = 0;
			isRoomOver = 0;
			for (int i = 0; i < getAlloc.size(); i++) {
				if (getAlloc.get(i).getSDateOfStay()
						.compareTo(allocDates.get(j)) == 0) {
					if (getAlloc.get(i).getIDomId() != 0 && isDomOver == 0) {
						isDomOver++;
						if (getAlloc.get(i).getSDateofcheckout() == null) {
							days = DateUtilities.noDaysDiffIn2Sets(
									date1,
									date2,
									DateUtilities.dbDateToCalDate(getAlloc.get(
											i).getSDateOfStay()), date2);
							days++;
						} else {
							days = DateUtilities.noDaysDiffIn2Sets(
									date1,
									date2,
									DateUtilities.dbDateToCalDate(getAlloc.get(
											i).getSDateOfStay()),
									DateUtilities.dbDateToCalDate(getAlloc.get(
											i).getSDateofcheckout()));
							days++;
						}
						if (days > 0) {
							amount += (days * getAlloc.get(i).getIAmount());
							doms += getAlloc.get(i).getIDomId() + "("
									+ getAlloc.get(i).getIRoomId() + ")("
									+ days + ")("
									+ getAlloc.get(i).getIAmount() + "),";
						}
					} else if (getAlloc.get(i).getIRoomId() != 0
							&& isRoomOver == 0
							&& getAlloc.get(i).getIDomId() == 0) {
						isRoomOver++;
						if (getAlloc.get(i).getSDateofcheckout() == null) {
							days = DateUtilities.noDaysDiffIn2Sets(
									date1,
									date2,
									DateUtilities.dbDateToCalDate(getAlloc.get(
											i).getSDateOfStay()), date2);
							days++;
						} else {
							days = DateUtilities.noDaysDiffIn2Sets(
									date1,
									date2,
									DateUtilities.dbDateToCalDate(getAlloc.get(
											i).getSDateOfStay()),
									DateUtilities.dbDateToCalDate(getAlloc.get(
											i).getSDateofcheckout()));
							days++;
						}
						if (days > 0) {
							amount += (days * getAlloc.get(i).getIAmount());
							rooms += getAlloc.get(i).getIRoomId() + "(" + days
									+ ")(" + getAlloc.get(i).getIAmount()
									+ "),";
						}
					} else if (getAlloc.get(i).getIDomId() != 0
							&& isDomOver > 0) {

						isDomOver++;
						if (getAlloc.get(i).getSDateofcheckout() == null) {
							days = DateUtilities.noDaysDiffIn2Sets(
									date1,
									date2,
									DateUtilities.dbDateToCalDate(getAlloc.get(
											i).getSDateOfStay()), date2);
							days++;
						} else {
							days = DateUtilities.noDaysDiffIn2Sets(
									date1,
									date2,
									DateUtilities.dbDateToCalDate(getAlloc.get(
											i).getSDateOfStay()),
									DateUtilities.dbDateToCalDate(getAlloc.get(
											i).getSDateofcheckout()));
							days++;
						}
						if (days > 0) {
							doms += getAlloc.get(i).getIDomId() + "("
									+ getAlloc.get(i).getIRoomId() + ")("
									+ days + ")("
									+ getAlloc.get(i).getIAmount() + "),";
						}
					}
				}
			}

		}
		com.bss.framework.FrontController.trace(doms);
		com.bss.framework.FrontController.trace(rooms);
		com.bss.framework.FrontController.trace("fromdate:" + date1);
		com.bss.framework.FrontController.trace("todate:" + DateUtilities.decCalDateBf8AM(date2));
		session.setAttribute("fromdate", date1);
		session.setAttribute("todate", DateUtilities.decCalDateBf8AM(date2));
		session.setAttribute("doms", doms);
		session.setAttribute("rooms", rooms);
		session.setAttribute("amount", amount);
		session.setAttribute("days", dateDiff + 1);
		return true;
	}

	public static ArrayList<Paymentsmade> findPaymentsMade(int transactionId)
			throws Exception {
		return PaymentDao.findPaymentsMade(transactionId);
	}

}
